<!-- 计分规则列表页 -->
<template>
    <search-table
      :columns="columns" :data="dataList"   
      :total="totalCount"
      :page.sync="query.pageIndex"
      :size.sync="query.pageSize"
      @change-page="changePage"
      @change-size="changeSize"
    >
      <!--       v-if="configMode !== 1" -->
      <template slot="button-group">
        <Button
          type="primary"
          ghost
          icon="md-add"
          :disabled="drillStatus == 3 || disabledAllBtn"
          class="mr15"
          @click="showAddOrUpdate('')"
        >
          添加计分规则
        </Button>
        <!-- {{ drillStatus }} -->
        <Upload
          ref="upload"
          :action="upload.uploadAction"
          :show-upload-list="false"
          :format="upload.format"
          :on-format-error="handleFormatError"
          :on-success="handleSuccessUpload"
          :before-upload="handleBeforeUpload"
          :headers="upload.uploadHeader"
        >
          <Button
            ghost
            type="primary"
            :disabled="upload.uploadList.length > 0 || disabledAllBtn || drillStatus != 1"
            style="height:32px;"
          >
            <div v-if="upload.uploadList.length == 0">
              <Icon type="ios-cloud-upload-outline"></Icon>
              <span>导入计分规则</span>
              <WarningTip
                :content="`请选择${upload.format.join('、')}格式文件导入`"
                style="position: relative;top:-1px;"
              ></WarningTip>
            </div>
            <div class="demo-upload-list" v-for="item in upload.uploadList">
              <Progress
                v-if="item.showProgress"
                :percent="item.percentage"
                hide-info
                style="width:100px"
              ></Progress>
            </div>
          </Button>
        </Upload>
        <!--  v-if="configMode !== 1" -->
        <Button
          type="primary"
          ref="downloadTemplateBtn"
          ghost
          icon="ios-cloud-download-outline"
          :disabled="disabledAllBtn"
          class="mr15"
        >
          <!--#57a3f3-->
          <a :href="downloadUrl" download="" style="color:#a5a5c6" @click.stop>模板下载</a>
        </Button>
      </template>
      <template slot="select-group">
        <Select filterable
          clearable
          placeholder="靶标类别"
          v-if="sceneType == 5"
          v-model="query.targetType"
          filterable
          @on-change="changePage(1)"
        >
          <Option :value="item.value" v-for="item in categoryArr" :key="item.value">{{
            item.label
          }}</Option>
        </Select>
        <Select filterable
          v-if="sceneType == 5 && typeExcel !== 11"
          clearable
          placeholder="针对方"
          v-model="query.contrapose"
          @on-change="changePage(1)"
        >
          <!-- <Option :value="item.value" v-for="item in contraposeArr" :key="item.value">{{
            item.label
          }}</Option> -->
          <Option  :value="1" v-if="typeExcel !== 11">防守方</Option>
          <Option  :value="2">攻击方</Option>
        </Select>
        <!-- <Select filterable clearable placeholder="加减分" v-model="query.subScore" @on-change="changePage(1)">
          <Option :value="item.value" v-for="item in subScoreArr" :key="item.value">{{
            item.label
          }}</Option>
        </Select> -->
        <Select filterable clearable placeholder="危险等级" v-model="query.grade" @on-change="changePage(1)">
          <Option :value="item.value" v-for="item in dangerLevelObj" :key="item.value">{{
            item.label
          }}</Option>
        </Select>
        <Select filterable
          v-if="sceneType == 5"
          clearable
          placeholder="计分方式"
          v-model="query.way"
          @on-change="changePage(1)"
        >
          <Option :value="item.value" v-for="item in wayArr" :key="item.value">{{
            item.label
          }}</Option>
        </Select>
        <!-- <Select filterable clearable placeholder="是否下线" v-model="query.online" @on-change="changePage(1)">
          <Option :value="item.value" v-for="item in booleanArr" :key="item.value">{{
            item.label
          }}</Option>
        </Select> -->
      </template>
      <template slot="input-group">
        <Input
          v-model.trim="query.category"
          clearable
          placeholder="类别"
          @on-change="debounceSearch"
        />
        <Input v-model.trim="query.mold" clearable placeholder="类型" @on-change="debounceSearch" />
      </template>
    <!-- 创建/修改 -->
    <Edit ref="editModal" :sceneType="sceneType" :sceneId="testId" @ok="handleOk" :typeExcel="typeExcel"></Edit>
  </search-table>
</template>
<script>
import encryption from '@/libs/encryption.js';
import { debounce } from '@/libs/utils';
import { queryHWScoreRule, deleteHWScoreRule } from '@/api/drill_compete.js';
import { scoreRuleMixin, categoryMixin } from '../mixins';
import SearchTable from '@/components/SearchTable/SearchTable';
import Edit from './edit.vue';
export default {
  name: 'SceneTemplate',
  components: { SearchTable,  Edit },
  mixins: [scoreRuleMixin, categoryMixin],
  props: {
    sceneType: {
      type: Number,
      default: 5
    },
    configMode: {
      type: Number,
      default: 0
    },
    disabledAllBtn: {
      type: Boolean,
      default: false
    },
    typeExcel:{
      type:Number,
      default:5 // 5：实网  7：综合  11：众测  15：仿真
    }
  },
  inject: ['parent'],
  data() {
    let September = sessionStorage.getItem('November');
    September = JSON.parse(encryption.SelfUseDecrypt(September));
    let testId = this.$route.query.id;
    return {
      USER_ID: September.userId,
      isRootDesigner: September.isRootDesigner,
      dataList: [], //规则列表
      totalCount: 0,
      loading: false,
      query: {
        pageIndex: 1,
        pageSize: 10,
        name: '',
        type: '',
        visibility: ''
      },
      createByMe: false,
      editModal: {
        show: false,
        data: {},
        type: 'import'
      },
      testId: testId,
      downloadUrl: `/api/compete/scoring/excel-template?type=${this.typeExcel}`,
      upload: {
        uploadAction: `/api/compete/scoring/${testId}`,
        uploadHeader: {
          Authorization: localStorage.token,
          Accept: '*/*'
        },
        format: ['xlsx'],
        uploadList: []
      },
      columns: [
        {
          title: '类别',
          key: 'category',
          tooltip: true,
          placement: 'top-left',
          width: 200
        },
        {
          title: '类型',
          key: 'mold',
          tooltip: true,
          placement: 'top-left',
          width: 400
        },
        {
          title: '靶标类别',
          key: 'targetType',
          width: 100,
          show: () => {
            return this.sceneType == 5;
          },
          render: (h, { row: { targetType } }) => {
            return h('span', this.filterCategory(targetType));
          }
        },
        {
          title: '针对方',
          key: 'contrapose',
          width: 100,
          show: () => {
            return this.sceneType == 5;
          },
          render: (h, { row: { contrapose } }) => {
            return h('span', this.filterContrapose(contrapose));
          }
        },
        // {
        //   title: '加减分',
        //   key: 'subScore',
        //   width: 100,
        //   render: (h, { row: { subScore } }) => {
        //     return h('span', this.filterSubscore(subScore));
        //   }
        // },
        {
          title: '危险等级',
          key: 'grade',
          width: 100,
          render: (h, { row: { grade } }) => {
            return h('span', this.filterLevel(grade));
          }
        },
        {
          title: '是否下线',
          key: 'line',
          width: 100,
          show: () => {
            return this.sceneType == 5;
          },
          render: (h, { row: { line } }) => {
            return h('span', line ? '是' : '否');
          }
        },
        {
          title: '分数',
          key: 'score',
          width: 100
        },
        {
          title: '计分方式',
          key: 'way',
          width: 100,
          show: () => {
            return this.sceneType == 5;
          },
          render: (h, { row: { way } }) => {
            return h('span', this.filterWay(way));
          }
        },
        {
          title: '描述',
          key: 'description',
          width: 200,
          tooltip: true
        },
        {
          title: '操作',
          key: 'action',
          width: 120,
          align: 'left',
          ellipsis: true,
          placement: 'top-right',
          order: 2,
          action: true,
          opList:[
              {
                  txt:'修改',
                  type:'modify',
                  disabled: () => {
                    return this.disabledAllBtn || this.drillStatus != 1
                  },
                  fun:this.showAddOrUpdate
              },
              {
                  txt:'删除',
                  type:'delete',
                  tooltip:true,
                  disabled: () => {
                    return this.disabledAllBtn || this.drillStatus != 1
                  },
                  fun:(data) => {
                      this.deleteHWScoreRule([data.id])
                  },
                  title: '你确定要删除吗?'
              }
          ],
          // render: (h, params) => {
          //   return h('div', [
          //     h(
          //       'Button',
          //       {
          //         props: {
          //           type: 'text',
          //           size: 'small',
          //           disabled: this.disabledAllBtn || this.drillStatus != 1
          //         },
          //         attrs: {
          //           title: '修改'
          //         },
          //         style: {
          //           background: 'none',
          //           border: 'none',
          //           boxShadow: 'none'
          //         },
          //         on: {
          //           click: () => {
          //             this.showAddOrUpdate(params.row);
          //           }
          //         }
          //       },
          //       [
          //         h('img', {
          //           attrs: {
          //             src:
          //               !this.disabledAllBtn && this.drillStatus == 1
          //                 ? require('../../../../../assets/project/modifys-h.png')
          //                 : require('../../../../../assets/project/modifys.png')
          //           },
          //           style: {
          //             cursor: 'pointer',
          //             'margin-right': '5px',
          //             'vertical-align': 'middle',
          //             display: 'inline-block',
          //             marginBottom: '4px'
          //           }
          //         })
          //       ]
          //     ),
          //     h(
          //       'Poptip',
          //       {
          //         props: {
          //           confirm: true,
          //           'ok-text': '确定',
          //           'cancel-text': '取消',
          //           type: 'error',
          //           size: 'large',
          //           title: '确定要删除这个规则吗?',
          //           transfer: true
          //         },
          //         style: {
          //           marginLeft: '0px'
          //         },
          //         on: {
          //           'on-ok': () => {
          //             this.deleteHWScoreRule([params.row.id]);
          //           }
          //         }
          //       },
          //       [
          //         h(
          //           'Button',
          //           {
          //             props: {
          //               type: 'text',
          //               size: 'small',
          //               disabled: this.disabledAllBtn || this.drillStatus != 1
          //             },
          //             attrs: {
          //               title: '删除'
          //             },
          //             style: {
          //               //              marginRight: '5px',
          //               background: 'none',
          //               border: 'none',
          //               boxShadow: 'none'
          //             }
          //           },
          //           [
          //             h('img', {
          //               attrs: {
          //                 src:
          //                   !this.disabledAllBtn && this.drillStatus == 1
          //                     ? require('../../../../../assets/project/delNote-h.png')
          //                     : require('../../../../../assets/project/delNote-d.png')
          //               },
          //               style: {
          //                 cursor: 'pointer',
          //                 'margin-right': '5px',
          //                 'vertical-align': 'middle',
          //                 display: 'inline-block',
          //                 marginBottom: '4px'
          //               }
          //             }),
          //             h('span', {
          //               style: {
          //                 cursor: 'pointer',
          //                 color:
          //                   !this.disabledAllBtn && this.drillStatus == 1 ? '#2d8cf0' : '#c5c8ce'
          //               }
          //             })
          //           ]
          //         )
          //       ]
          //     )
          //   ]);
          // }
        }
      ]
    };
  },
  computed: {
    drillStatus() {
      return this.parent.drillStatus;
    },
    compeedManagePanelShow() {
      return this.parent.compeedManagePanelShow;
    },
  },
  mounted() {
    this._query = { ...this.query };
    this.queryHWScoreRule();
  },
  methods: {
    queryHWScoreRule() {
      let query = { ...this.query };
      queryHWScoreRule(this.testId, query)
        .then(({ code, data, message }) => {
          if (code == 1) {
            this.dataList = data.items;
            this.totalCount = data.total;
          } else {
            this.$Message.error(message);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handleOk(type) {
      type === 'add' ? this.changePage(1) : this.queryHWScoreRule();
    },
    changePage(page) {
      this.query.pageIndex = page;
      this.queryHWScoreRule();
    },
    changeSize(val) {
      this.query.pageSize = val
      this.queryHWScoreRule();
    },
    debounceSearch: debounce(function() {
      this.changePage(1);
    }, 500),
    refreshList() {
      this.createByMe = false;
      this.query = { ...this._query, pageSize: this.query.pageSize };
      this.queryHWScoreRule();
    },
    handleFormatError() {
      this.upload.uploadList = [];
      this.$Message.warning('文件格式错误');
    },
    handleBeforeUpload(file) {
      // const fileSize = file.size / 1024 / 1024 > this.$store.state.common.fileMax;
      // if(fileSize){
      //   this.$Message.error({
      //     content: `文件大小不能大于${this.$store.state.common.fileMax}M`,
      //     duration: 2
      //   });
      // return false;
      // }
      this.upload.uploadList = this.$refs.upload.fileList;
      return true;
    },
    handleSuccessUpload(res) {
      this.upload.uploadList = [];
      if (res.code == 1) {
        this.$Message.info('导入成功');
        this.refreshList();
      } else {
        this.$Message.warning(res.message);
      }
    },
    exportTemplate(obj) {
      const msg = this.$Message.loading({
        content: '正在导出...',
        duration: 0
      });
      let { id, name } = obj;
      exportSceneTemplate(id)
        .then((data) => {
          setTimeout(msg, 100);
          if (!data.code) {
            const downloadElement = document.createElement('a');
            const href = window.URL.createObjectURL(data);
            downloadElement.href = href;
            downloadElement.download = `${name}.json`;
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放掉blob对象
          } else {
            this.$Message.error('导出失败');
          }
        })
        .catch((error) => {
          setTimeout(msg, 100);
          this.$Message.error('导出失败');
        });
    },
    // 显示修改modal
    showAddOrUpdate(data) {
      // if (this.disabledAllBtn) {
      //   return;
      // }
      this.$refs.editModal.showModal(data);
    },
    deleteHWScoreRule(id) {
      deleteHWScoreRule(id)
        .then(({ code, data, message }) => {
          if (code == 1) {
            this.$Message.info('删除成功');
            if (this.query.pageIndex > 1 && this.totalCount == 1) {
              this.query.pageIndex--;
            }
            this.queryHWScoreRule();
          } else {
            this.$Message.error(message);
          }
        })
        .catch((e) => {
          this.$Message.error(message);
        });
    },
    // 按钮点击状态
    setReBtnStatus(params) {
      let userid = params.creator;
      if ((userid === this.USER_ID || this.isRootDesigner) && params.visibility != 'public') {
        return false;
      } else {
        return true;
      }
    }
  }
};
</script>
<style scoped>
.pageWrap {
  margin: 30px;
  background: #fff;
  height: calc(100vh - 60px);
  border-radius: 10px;
}

.pageHeader {
  padding: 20px 20px 0 20px;
}

.pageHeader .title {
  float: left;
  font-size: 18px;
}

.fixedHeightTable {
  margin: 20px 20px 0 20px;
}
.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.flex-end {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  flex-wrap: wrap;
}
.contents .cardlist{
  overflow: visible !important;
}
</style>
